<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - 移动专项测试平台</title>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui@2.15.14/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background-color: #f0f2f5;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .login-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            width: 400px;
            padding: 40px;
            margin: 20px;
        }
        .login-title {
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 30px;
        }
        .login-form {
            width: 100%;
        }
        .form-item {
            margin-bottom: 20px;
        }
        .form-button {
            width: 100%;
        }
        .login-tabs {
            margin-bottom: 20px;
        }
        .qrcode-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        .qrcode-image {
            width: 200px;
            height: 200px;
            margin-bottom: 20px;
            border: 1px solid #e4e7ed;
            padding: 10px;
        }
        .qrcode-loading {
            width: 200px;
            height: 200px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border: 1px solid #e4e7ed;
            padding: 10px;
            margin-bottom: 20px;
        }
        .qrcode-tip {
            text-align: center;
            color: #606266;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .register-link {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
            color: #606266;
        }
        .register-link a {
            color: #409EFF;
            text-decoration: none;
        }
        .el-tabs__nav {
            justify-content: center;
        }
        .el-tabs__item {
            flex: 1;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-title">移动专项测试平台</div>
        
        <div id="app">
            <el-tabs v-model="activeTab" class="login-tabs">
                <el-tab-pane label="账号密码登录" name="password">
                    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
                        <el-form-item label="手机号" prop="phone" class="form-item">
                            <el-input v-model="loginForm.phone" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password" class="form-item">
                            <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" prefix-icon="el-icon-lock"></el-input>
                        </el-form-item>
                        <el-form-item class="form-item">
                            <el-button type="primary" @click="handleLogin" :loading="loginLoading" class="form-button">登录</el-button>
                        </el-form-item>
                    </el-form>
                    <div class="register-link">
                        还没有账号？<a href="javascript:void(0)" @click="switchToRegister">立即注册</a>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="微信扫码登录" name="wechat">
                    <div class="qrcode-container">
                        <img v-if="qrcodeUrl" :src="qrcodeUrl" alt="微信扫码登录" class="qrcode-image">
                        <div v-else class="qrcode-loading">
                            <el-icon><loading /></el-icon>
                            <span>正在生成二维码...</span>
                        </div>
                        <div class="qrcode-tip">{{ qrcodeStatus }}</div>
                        <div class="qrcode-tip" style="margin-top: 10px;">如二维码已过期，点击<a href="javascript:void(0)" @click="refreshQRCode" style="color: #409EFF;">刷新</a></div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>

    <!-- 引入Vue 2.x和Element UI -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.14/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.8/dist/axios.min.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    activeTab: 'password',
                    loginForm: {
                        phone: '',
                        password: ''
                    },
                    loginRules: {
                        phone: [
                            { required: true, message: '请输入手机号', trigger: 'blur' },
                            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
                        ],
                        password: [
                            { required: true, message: '请输入密码', trigger: 'blur' },
                            { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
                        ]
                    },
                    loginLoading: false,
                    // 微信扫码登录相关状态
                    qrcodeUrl: '/static/images/qrcode-placeholder.svg',
                    sessionId: null,
                    qrcodeStatus: '',
                    remainingTime: 0,
                    qrcodeExpireTime: 180, // 二维码过期时间(秒)
                    checkTimer: null,
                    countdownTimer: null
                };
            },
            methods: {
                handleLogin() {
                    this.$refs.loginForm.validate((valid) => {
                        if (valid) {
                            this.loginLoading = true;
                            axios.post('/api/login', this.loginForm)
                                .then(response => {
                                    this.loginLoading = false;
                                    if (response.data.success) {
                                        this.$message.success('登录成功');
                                        // 存储token并跳转到首页
                                        localStorage.setItem('token', response.data.token);
                                        window.location.href = '/';
                                    } else {
                                        this.$message.error(response.data.message);
                                    }
                                })
                                .catch(error => {
                                    this.loginLoading = false;
                                    this.$message.error('登录失败，请稍后重试');
                                    console.error(error);
                                });
                        }
                    });
                },
                switchToRegister() {
                    window.location.href = '/register';
                },
                refreshQRCode() {
                    // 清除之前的定时器
                    this.clearTimers();
                    // 获取新的二维码
                    this.getWechatQRCode();
                },
                getWechatQRCode() {
                    // 先显示加载状态
                    this.qrcodeUrl = null;
                    this.qrcodeStatus = '正在生成二维码...';
                    
                    axios.get('/api/wechat/qrcode')
                        .then(response => {
                            if (response.data.success) {
                                this.qrcodeUrl = response.data.qrcode_url;
                                this.sessionId = response.data.session_id;
                                this.qrcodeStatus = '请使用微信扫描二维码登录';
                                this.remainingTime = this.qrcodeExpireTime;
                                // 开始检查登录状态
                                this.startCheckingLoginStatus();
                                // 开始倒计时
                                this.startCountdown();
                            } else {
                                this.$message.error('获取二维码失败，请稍后重试');
                                // 请求失败时，重置为占位图片
                                this.qrcodeUrl = '/static/images/qrcode-placeholder.svg';
                                this.qrcodeStatus = '二维码获取失败，请点击刷新';
                            }
                        })
                        .catch(error => {
                            this.$message.error('获取二维码失败，请稍后重试');
                            console.error(error);
                            // 网络错误时，重置为占位图片
                            this.qrcodeUrl = '/static/images/qrcode-placeholder.svg';
                            this.qrcodeStatus = '网络连接失败，请检查网络后重试';
                        });
                },
                startCheckingLoginStatus() {
                    // 每3秒检查一次登录状态
                    this.checkTimer = setInterval(() => {
                        this.checkLoginStatus();
                    }, 3000);
                },
                checkLoginStatus() {
                    axios.get(`/api/wechat/login_status/${this.sessionId}`)
                        .then(response => {
                            if (response.data.success) {
                                if (response.data.status === 'scanned') {
                                    this.qrcodeStatus = '已扫描，请在微信中确认登录';
                                } else if (response.data.status === 'confirmed') {
                                    // 登录成功
                                    this.qrcodeStatus = '登录成功，正在跳转...';
                                    this.clearTimers();
                                    
                                    // 存储token并跳转到首页
                                    if (response.data.user_info && response.data.user_info.token) {
                                        localStorage.setItem('token', response.data.user_info.token);
                                    }
                                    window.location.href = '/';
                                } else if (response.data.status === 'expired') {
                                    this.qrcodeStatus = '二维码已过期，请点击刷新';
                                    this.clearTimers();
                                }
                            } else {
                                this.qrcodeStatus = '获取状态失败：' + (response.data.message || '未知错误');
                                this.clearTimers();
                            }
                        })
                        .catch(error => {
                            console.error('检查登录状态失败:', error);
                        });
                },
                startCountdown() {
                    this.countdownTimer = setInterval(() => {
                        this.remainingTime--;
                        if (this.remainingTime <= 0) {
                            this.qrcodeStatus = '二维码已过期，请点击刷新';
                            this.clearTimers();
                        }
                    }, 1000);
                },
                clearTimers() {
                    if (this.checkTimer) {
                        clearInterval(this.checkTimer);
                        this.checkTimer = null;
                    }
                    if (this.countdownTimer) {
                        clearInterval(this.countdownTimer);
                        this.countdownTimer = null;
                    }
                }
            },
            watch: {
                activeTab(newTab) {
                    // 切换到微信登录标签时，自动获取二维码
                    if (newTab === 'wechat' && !this.qrcodeUrl) {
                        this.getWechatQRCode();
                    } else if (newTab !== 'wechat') {
                        // 切换到其他标签时，清除定时器
                        this.clearTimers();
                    }
                }
            },
            mounted() {
                // 如果初始标签是微信登录，自动获取二维码
                if (this.activeTab === 'wechat') {
                    this.getWechatQRCode();
                }
            },
            beforeDestroy() {
                // 组件销毁时清除定时器
                this.clearTimers();
            }
        });
    </script>
</body>
</html>